<template>
  <div id="app">
<el-card shadow="always">
  <!--条件查询-->
  <el-form :inline="true" size="medium" :model="employeeSearch" class="demo-form-inline">
    <el-form-item>
      <el-input v-model="employeeSearch.ename" placeholder="员工姓名"></el-input>
    </el-form-item>
    <el-form-item>
      <el-select v-model="employeeSearch.sex" placeholder="员工性别">
        <el-option label="性别" value="0"></el-option>
        <el-option label="男" value="男"></el-option>
        <el-option label="女" value="女"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-select v-model="employeeSearch.did" placeholder="员工部门">
        <el-option label="所有部门" value="0"></el-option>
        <el-option :label="c.dname" :value="c.did" v-for="c in departmentList" :key="c.did"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" icon="el-icon-plus" plain @click="addEmployee">添加员工</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
    </el-form-item>
  </el-form>
  <el-table
      :data="employeeList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
  >
    <el-table-column
        type="selection">
    </el-table-column>
    <el-table-column
        prop="eid"
        label="工号"
        align="center"
        width="100">
    </el-table-column>
    <el-table-column
        prop="ename"
        label="员工姓名"
        align="center"
        width="100">
    </el-table-column>
      <el-table-column
          prop="sex"
          label="员工性别"
          align="center"
          width="100">
      </el-table-column>
        <el-table-column
            prop="age"
            label="员工年龄"
            align="center"
            width="100">
        </el-table-column>
          <el-table-column
              prop="addr"
              label="员工家庭住址"
              align="center"
              width="200">
          </el-table-column>
            <el-table-column
                prop="phone"
                label="员工电话号码"
                align="center"
                width="250">
            </el-table-column>
              <el-table-column
                  prop="did"
                  label="员工所属部门"
                  align="center"
                  width="120">
              </el-table-column>
    <el-table-column label="操作" align="center" width="200">
      <template slot-scope="scope">
        <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.$index, scope.row)">编辑
        </el-button>
        <el-button
            type="success"
            size="small"
            @click="handleDelete(scope.$index, scope.row)">删除
        </el-button>
      </template>
    </el-table-column>
 </el-table>
  <!--分页导航-->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[1,,5,10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="100">
  </el-pagination>
</el-card>
    <!--添加、修改信息共用一个对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="employee" :rules="rules" ref="ruleForm">
        <el-form-item label="员工姓名" prop="ename" :label-width="formLabelWidth">
          <el-input v-model="employee.ename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="employee.sex" label="男">男</el-radio>
          <el-radio v-model="employee.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="employee.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工地址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="employee.addr" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone" :label-width="formLabelWidth">
          <el-input v-model="employee.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工部门" prop="did" :label-width="formLabelWidth">
          <el-select v-model="employee.did" placeholder="请选择所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="c.dname" :value="c.did" v-for="c in departmentList" :key="c.did"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEmployee">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
#app{
  display: flex;
  justify-content: center;
}
.el-pagination{
  text-align: right;
  margin-top: 20px;
}
</style>
<script>
import employeeApi from "@/api/employeeApi"
import departmentApi from "@/api/departmentApi";
export default {
  data() {
    //年龄的定义规则
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄必须在1-200之间'))
      } else {
        callback()
      }
    }
    //电话号码的定义规则
    let checkPhoneNumber = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('电话号码不能为空'));
      } else if (!/^\d{11}$/.test(value)) {
        return callback(new Error('电话号码必须是11位数字'));
      } else if (value.charAt(0) !== '1') {
        return callback(new Error('电话号码必须以1开头'));
      } else {
        callback();
      }
    }


    return {
      employeeList:[],
      page:1,
      pageSize:1,
      total:100,
      dialogFormVisible:false //控制编辑框是否显示
    , employeeSearch:{}, // 查询条件对象
      departmentList: [],   // 所有部门
      multipleSelection:[],     // 代表选中的多项
      eids: [],                 // 删除员工的工号
      employee:{} //修改的员工信息
      ,title:'添加员工',
      formLabelWidth: '100px',
      // 定义校验规则
      rules: {
        ename: [
          {required: true, message: '请输入员工姓名', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        age: [// 使用自定义验证规则验证年龄
          { validator : checkAge, trigger: 'blur'}
        ],
        phone:[//使用自定义验证规则验证电话号码
          { validator : checkPhoneNumber, trigger: 'blur'}
        ],
        addr: [
          {required: true, message: '请输入员工住址', trigger: 'blur'},
        ],
        did: [
          {required: true, message: '请选择员工部门 ', trigger: 'blur'},
        ]
      }
  }
  },
  created() {
    this.findByPage()
//this.search()
    this.findAllDepartments()
  },
  methods:{
    //1.查询所有员工
    async findEmployees(){
      const {data:res}
          =await  employeeApi.findALLEmployees()
if(res.code===200)
{this.employeeList=res.data.list}},
    // 2. 分页查询
    async findByPage() {
      const {data:res} = await employeeApi.findByPage(this.page,this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.employeeList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 查询所有部门
    async findAllDepartments() {
      const {data: res} = await departmentApi.findAllDepartments()
      console.log(res)
      if (res.code === 200) {
        this.departmentList = res.data.list
      }
    },
    //条件分页查询
    async search() {
      console.log(this.employeeSearch.sex)
      const {data: res} = await employeeApi.search(this.page, this.pageSize, this.employeeSearch)
      console.log(res)
      if (res.code === 200) {
        this.employeeList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    //删除
    handleDelete(index, row) {
      this.eids = []
      if(row){  // 删除单个
        this.eids.push(row.eid)
      }else{
        this.eids = this.multipleSelection.map(m => m.eid)
      }
      this.$confirm(`是否真的要删除工号为${this.eids}的员工吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {       // 点击了"确定"按钮后执行
        let _this = this
        employeeApi.deleteEmployee(this.eids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {     // 点击了"取消"按钮后执行
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 点击编辑键后
    handleEdit(index, row) {
      this.title = '修改员工信息'
      this.employee = row
      this.dialogFormVisible = true
      console.log(index, row);
    },
    //点击添加键后
    addEmployee() {
      this.title = "添加员工"
      this.employee = {}
      this.dialogFormVisible = true
    },
    //保存所有修改的信息--包括编辑和添加
    saveEmployee() {
      this.$refs.ruleForm.validate(async valid => {
        let url = "/employee/add"      // 默认地址是添加
        let method = "post"
        if(this.employee.eid){
          url = "/employee/update"    // 如果有值就改为修改
          method = "put"
          console.log("update")
        }
        // 向后端发送请求,执行添加或修改
        if (valid) {
          console.log(url,method)
          const {data:res} = await employeeApi.save(url,method,this.employee)
          console.log("res:",res)
          if (res.code === 200) {     // 后端执行成功返回200
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {        // 关闭对话框时的回调
                // 6.3 关闭对话框
                this.dialogFormVisible = false
                // 6.4 重新查询
                this.search()
              }
            })
          }else{                      // 后端执行失败返回500
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    // 当pagesize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
           this.page = val
      this.search()
      console.log(`当前页: ${val}`);
    }
  }
}
</script>